const express=require('express')
const pool=require('../pool')
const  router=express.Router()

// 用户注册
router.post('/reg',(req,res,next)=>{
  let obj=req.body
  let sql='insert into sm_user set ?'
  pool.query(sql,[obj],(err,data)=>{
    if(err){next(err);return}
    if(data.affectedRows==0){
      res.send({
        code:0,
        msg:'注册失败'
      })
    }else{
      res.send({
        code:1,
        msg:'注册成功'
      })
    }
  })
})


// 用户登录
router.post('/login',(req,res,next)=>{
  let obj=req.body
  let sql='select * from sm_user where phone=? and upwd=?'
  pool.query(sql,[obj.phone,obj.upwd],(err,data)=>{
    if (err) {
      next(err);
      return
    }
    if (data.length == 0) {
      res.send({
        code: 0,
        msg: "没找到该用户"
      })
    } else {
      res.send({
        code: 1,
        msg: "登录成功"
      })
    }  
  })
})

// 用户修改信息
router.put('/edit',(req,res,next)=>{
  let obj=req.body
  let sql=`update sm_user set uname="${obj.uname}",phone="${obj.phone}",upwd=${obj.upwd} where phone="${obj.oldphone}";`
  pool.query(sql,(err,data)=>{
    if(err){next(err);return}
    if(data.affectedRows == 1){
      res.send({
        code:1,
        msg:'修改成功'
      })
    }
  })

})

module.exports=router